package com.dao;

import java.sql.Date;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.model.Branch;
import com.model.Prize;

@Repository("prizeDao")
public class PrizeDaoImpl implements PrizeDao{

	@Autowired
	private SessionFactory sessionFactory;
	public Session getSession()
	{
		return sessionFactory.getCurrentSession();
	}
	@Override
	public void add(Integer branchId,Prize prize) {
		Session session= sessionFactory.getCurrentSession();
		session.beginTransaction();
		Branch branch=(Branch)session.get(Branch.class, branchId);
		prize.setBranch(branch);
		session.save(prize);
		session.flush();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Prize> getAll(int page) {
		return getSession().createCriteria(Prize.class) 
				.addOrder(Order.desc("prizeId"))
				.setFirstResult((page-1) * 5).setMaxResults(5).setFetchSize(5)
				.list(); 
				
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Prize> getAll() {
		return (List<Prize>) getSession().createCriteria(Prize.class).list();	
	}

	@Override
	public Prize get(Integer id) {
		return (Prize)getSession().get(Prize.class, id);	
	}

	@Override
	public void delete(Integer id) {

		Prize prize= (Prize) getSession().get(Prize.class, id);
			getSession().delete(prize);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Prize> getByDate(Date from, Date to) {
		Criteria criteria = getSession().createCriteria(Prize.class);
		if (from != null) {
			criteria.add(Expression.ge("date",from));
		}
		if (to != null) {
			criteria.add(Expression.le("date",to));
		}
		
		return criteria.list();
	}

	@Override
	public int getNoOfRecords() {
		return ((Number) getSession().createQuery("select count(*) from Prize").uniqueResult()).intValue();
	}


}
